package role

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"net/http"
	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ApisLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewApisLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApisLogic {
	return &ApisLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ApisLogic) Apis(req *types.RoleRequest) (resp *types.RoleApisResponse, err error) {
	resp = new(types.RoleApisResponse)

	role := fmt.Sprintf("role_%d", req.Id)

	perms := l.svcCtx.Enforcer.GetPermissionsForUser(role)
	fmt.Println("权限列表：", perms)
	fmt.Println("权限列表数量：", len(perms))

	var g errgroup.Group
	for _, perm := range perms {
		if perm[0] != role {
			fmt.Println("忽略权限：", perm)
			continue
		}

		uri, method := perm[1], perm[2]
		g.Go(func() error {
			var apiId int64
			tx := l.svcCtx.DB.WithContext(l.ctx).Raw(fmt.Sprintf("select id from api where uri='%s' and method='%s'", uri, method)).Scan(&apiId)
			if tx.Error != nil {
				fmt.Printf("[Error]查询api[%s][%s]：%s\n", method, uri, tx.Error.Error())
				return tx.Error
			}

			//fmt.Printf("[Debug]api[%s][%s]:id[%d]\n", method, uri, apiId)
			resp.Data = append(resp.Data, apiId)
			return nil
		})

	}

	err = g.Wait()
	if err != nil {
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"

	return resp, nil
}
